package com.qumitech.visualnovel.component.concurrent;

import java.util.HashMap;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 分段锁，系统提供一定数量的原始锁，根据传入的key获取对应的锁并加锁
 * 去除原作者使用hashcode作为key
 * @author http://www.codeceo.com/article/java-3-lock.html
 * @date 2017-11-30
 */
public class SegmentLock {
    /** 默认分段数量 */
    private Integer segments = 16;
    private final HashMap<Integer, ReentrantLock> lockMap = new HashMap<>();

    public SegmentLock() {
        init(null, false);
    }

    public SegmentLock(Integer counts, boolean fair) {
        init(counts, fair);
    }

    private void init(Integer counts, boolean fair) {
        if (counts != null) {
            segments = counts;
        }
        for (int i = 0; i < segments; i++) {
            lockMap.put(i, new ReentrantLock(fair));
        }
    }

    public void lock(int key) {
        ReentrantLock lock = lockMap.get(key % segments);
        lock.lock();
    }

    public void unlock(int key) {
        ReentrantLock lock = lockMap.get(key % segments);
        lock.unlock();
    }
}

